package com.ciwong.epaper.modules.me.ui;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ciwong.ciwongwrite.utils.CWUtils;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.event.EventBusFactory;
import com.ciwong.epaper.modules.cordva.BaseHtmlActicity;
import com.ciwong.epaper.modules.cordva.SubmitEvent;
import com.ciwong.epaper.modules.epaper.util.MyWebViewClient;
import com.ciwong.epaper.modules.homework.bean.PublishWorkRecords;
import com.ciwong.epaper.modules.me.bean.ShareWork;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.share.WxShareHelper;
import com.ciwong.epaper.modules.share.WxShareListener;
import com.ciwong.epaper.modules.share.bean.ShareMsgObj;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.HttpRequest;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.LogOutUtil;
import com.ciwong.epaper.widget.PlayStateView;
import com.ciwong.epaper.widget.toast.ZToast;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.audio.recorder.Mp3Recorder;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.utils.FileUtil;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.google.gson.Gson;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:班级成绩页面（跳转网页）
 * @author: wyk
 * @time: 2021/5/21 11:00
 */
public class ClassGradesActivity extends BaseHtmlActicity {

    private static final String TAG = "ClassGradesActivity";
    private String reviceObject, workId, workName, accessToken;
    private int subjectId, examMode;
    private int batchId;
    private long publishDate, effectiveDate;
    private PublishWorkRecords publishWorkRecords;
    private String startURL;
    private BridgeWebView bridgeWebView;
    private Dialog recordBottomDialog;
    private PlayStateView publish_dk_audio_stateView;
    private TextView dk_audio_complete;
    private ImageView img_stop_recording;
    //音频地址
    private String tempMusicPath = "";

    private String savePicUrl = "";

    //是否录音
    private boolean isRecord = false;

    private final static String TAG_AUDIO = "tag_audio";
    private CWDialog getRecordPermissDialog;
    private final int CODE_REQUEST_RECORD_AUDIO_PERMISSION = 8801;
    protected Mp3Recorder mp3Recorder;

    //上传阿里云音频地址
    private String aliyunAudioUri;
    //是否录音失败
    protected boolean isRecordFail = false;
    private double mVolume = -1.0;
    private String downloadMsg = "";
    private Handler handler = new Handler(Looper.getMainLooper());
    private Handler aliyunHandler = new Handler(Looper.getMainLooper());
    private ShareWork shareParams = new ShareWork();
    private Gson gson = new Gson();
    /**
     * 监听上传
     */
    private ALiYunManager.ALiYunListener aLiYunListener = new ALiYunManager.ALiYunListener() {

        @Override
        public void onProgress(Object tag, long currentSize, long totalSize) {
            if (tag != null) {
                try {
                    String photoPath = tag.toString();
                    if (TAG_AUDIO.equals(photoPath)) {
                        if (currentSize > 0 && totalSize > 0) {
                            long progress = currentSize * 100 / totalSize;
                            if (progress < 100) {
                                updateDownloadProgress((int) progress);
                            }
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        @Override
        public void onSuccess(Object tag, String url) {
            if (tag != null) {
                try {
                    hideDownloadProgress();
                    String photoPath = tag.toString();
                    if (TAG_AUDIO.equals(photoPath)) {
                        aliyunAudioUri = url;
                        aliyunHandler.post(getUpdateRecordPath);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(Object tag, int errorCode) {
            if (tag != null) {
                try {
                    String photoPath = String.valueOf(tag);
                    if (photoPath.equals(tempMusicPath)) {
                        hideDownloadProgress();
                        ZToast.makeText(ClassGradesActivity.this,
                                "上传失败，请稍后重试！", ZToast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    };

    private Handler mRecorderHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (isFinishing()) {
                return;
            }
            switch (msg.what) {
                case Mp3Recorder.MSG_REC_STARTED:// 录音开始
                    /*img_micro_recording.setVisibility(View.VISIBLE);
                    Drawable drawable = img_micro_recording.getDrawable();
                    if (drawable != null && drawable instanceof AnimationDrawable) {
                        ((AnimationDrawable) drawable).start();
                    }
*/
                    break;
                case Mp3Recorder.MSG_DB:// 录音分贝
                    Bundle b = msg.getData();
//                    Log.d(TAG, "###########Mp3Recorder.MSG_DB############" + Mp3Recorder.MSG_DB);
                    if (b != null) {
                        double db = b.getDouble("db");
                        if (db >= 0) {
                            Log.d(TAG, "###########db############" + db);
                            mVolume = db;
                        }
//                        Log.d(TAG, "###########db############" + db);

//                        if (microRecording != null && !Double.isNaN(db)) {
//                            microRecording.setRms(db);
//                        }
                    }
                    break;
                case Mp3Recorder.MSG_ERROR_AUDIO_RECORD:// 录音失败
                    isRecordFail = true;
                    Log.d(TAG, "###########Mp3Recorder.MSG_ERROR_AUDIO_RECORD############" + Mp3Recorder.MSG_ERROR_AUDIO_RECORD);
                    DialogUtil.showSettingPermissions(ClassGradesActivity.this);
                    break;

                case Mp3Recorder.MSG_ERROR_REC_START:
                    isRecordFail = true;
                    Log.d(TAG, "###########Mp3Recorder.MSG_ERROR_REC_START############" + Mp3Recorder.MSG_ERROR_AUDIO_RECORD);

                    DialogUtil.showSettingPermissions(ClassGradesActivity.this);
                    break;
                case Mp3Recorder.MSG_REC_STOPPED:// 录音结束
                    /*img_micro_recording.setVisibility(View.GONE);
                    Drawable drawable2 = img_micro_recording.getDrawable();
                    if (drawable2 != null && drawable2 instanceof AnimationDrawable) {
                        ((AnimationDrawable) drawable2).stop();
                    }*/
                    break;
                default:
                    break;
            }
        }

    };
    private Runnable stopRecordRunnable = new Runnable() {
        public void run() {
            stopRecord();
        }
    };
    private Runnable getUpdateRecordPath = new Runnable() {
        @Override
        public void run() {
            getUpdateRecordPath();
        }
    };

    public void getUpdateRecordPath() {
        bridgeWebView.callHandler("getUpdateRecordPath", aliyunAudioUri, new CallBackFunction() {
            @Override
            public void onCallBack(String data) {

            }
        });
        aliyunHandler.removeCallbacks(getUpdateRecordPath);
    }

    @Override
    protected int setView() {
        return R.layout.activity_student_grades;
    }

    @Override
    protected void findViews() {
        bridgeWebView = findViewById(R.id.dk_work_details_webview);
    }

    @Override
    protected void preCreate() {
        super.preCreate();
        Intent intent = getIntent();
        publishWorkRecords = (PublishWorkRecords) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
        publishDate = publishWorkRecords.getPublishDate();
        effectiveDate = publishWorkRecords.getEffectiveDate();
        reviceObject = publishWorkRecords.getWorkList().get(0).getReviceObject();
        workId = publishWorkRecords.getWorkList().get(0).getWorkId();
        workName = publishWorkRecords.getWorkName();
        subjectId = publishWorkRecords.getWorkList().get(0).getSubjectId();
        batchId = publishWorkRecords.getBatchId();
        examMode = publishWorkRecords.getExamMode();
    }

    @Override
    protected void init() {
        super.init();
        setValideSource(false);
        if (null != workName && !"".equals(workName)) {
            setTitleText(workName);
        } else {
            setTitleText("作业详情");
        }

        BaseRequest.VerifyInfo verifyInfo = HttpRequest.getVerifyInfo();
        if (verifyInfo != null) {
            String clientId = verifyInfo.getClientId();
            accessToken = verifyInfo.getAccessToken();
            String userId = EApplication.getInstance().getUserInfoBase().getUserId() + "";
            String brandId = EApplication.BRAND_ID + "";
            String workNameUtf8 = toUtf8(workName);
            reviceObject = toUtf8(reviceObject);
            if (publishWorkRecords.getExamMode() == 0 || publishWorkRecords.getExamMode() == 2) {
                startURL = EpaperConstant.URL_H5_CLASS_GRADES + publishDate + "/" + effectiveDate + "/" + reviceObject + "/" + workId + ":/" + workNameUtf8 + "/" + subjectId + "?brandId=" + brandId + "&clientId=" + clientId + "&userId=" + userId + "&accessToken=" + accessToken + "&state=" + 3 + "&wappid=wx1370631eb280be21";
            } else if (publishWorkRecords.getExamMode() == 1) {
                startURL = EpaperConstant.URL_H5_CLASS_GRADES_COMPUTER + publishDate + "/" + effectiveDate + "/" + reviceObject + "/" + workId + ":/" + workNameUtf8 + "/" + subjectId + "/" + batchId + "?brandId=" + brandId + "&clientId=" + clientId + "&userId=" + userId + "&accessToken=" + accessToken + "&state=" + 3 + "&wappid=wx1370631eb280be21";
            }
//            setStartURL(startURL);
//            loadUrl(startURL);
            CWLog.d("byou", startURL);
            bridgeWebView.setDefaultHandler(new DefaultHandler());
            bridgeWebView.setWebChromeClient(new WebChromeClient());
            bridgeWebView.getSettings().setJavaScriptEnabled(true);
            bridgeWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            bridgeWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
            //settings.setPluginsEnabled(true);
            bridgeWebView.getSettings().setAllowFileAccess(true);
            bridgeWebView.getSettings().setLoadWithOverviewMode(true);
            bridgeWebView.getSettings().setUseWideViewPort(true);
            bridgeWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
            bridgeWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
            //开启DOM storage 存储
            bridgeWebView.getSettings().setDomStorageEnabled(true);
            //设置webSettings，允许其加载混合网络协议内容

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                bridgeWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
            bridgeWebView.loadUrl(startURL);
            //设置webSettings，允许其加载混合网络协议内容
            bridgeWebView.setWebViewClient(new MyWebViewClient(bridgeWebView));
            bridgeWebView.setWebViewClient(new MyWebViewClient(bridgeWebView) {
                                               @Override
                                               public void onPageFinished(WebView view, String url) {
                                                   if (url.indexOf(EpaperConstant.URL_H5_CLASS_GRADES) == -1) {
                                                       Log.d("---hide", url);
                                                       //隐藏分享按钮
                                                       hideRightBtn();
                                                   }
                                                   super.onPageFinished(view, url);
                                               }
                                           }
            );

            //通知录音
            bridgeWebView.registerHandler("callUpdateRecord", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    showRecordBottomDialog();
                    //getUpdateRecordPath();
                }
            });
            //通知作业列表有撤回
            bridgeWebView.registerHandler("notifyHomeworkRecall", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    EventBus.getDefault().post(new EventBusFactory.ReflushWorkEvent(examMode));
                    finish();
                }
            });
            //分享到微信 返回数据回调
            bridgeWebView.registerHandler("callNativeShare", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    CWLog.d("--- ", data);
                    if (data != null) {
                        shareParams = gson.fromJson(data, ShareWork.class);
                    }
                    setRightBtnBG(R.mipmap.work_share);
                    setRightBtnListener(new ViewOnClickListener() {
                        @Override
                        public void avertRepeatOnClick(View v) {
                            showshareBottomDialog();
                        }
                    });
                }
            });
            bridgeWebView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    final WebView.HitTestResult hitTestResult = bridgeWebView.getHitTestResult();
                    // 如果是图片类型或者是带有图片链接的类型
                    if (hitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE ||
                            hitTestResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                        savePicUrl = hitTestResult.getExtra();//获取图片链接
                        // 弹出保存图片的对话框
                        saveAlbumDialog();
                        return true;
                    }
                    return false;
                }
            });
            ALiYunManager.getInstance().registerListener(aLiYunListener);
        } else {
            showToastError(getString(R.string.get_user_info_error));
            finish();
        }
    }

    /**
     * 保存图片到相册
     */
    private void saveAlbumDialog() {
        final CWDialog dialog = new CWDialog(this, false, false);
        dialog.setTitle("提示");
        dialog.setTitleTextColor(Color.BLACK);
        dialog.setMessage("保存图片到相册", 16, Color.BLACK);
        dialog.setPositiveButton(android.R.string.ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface interDialog,
                                        int which) {
                        if (Build.VERSION.SDK_INT < 29) {
                            showGetPermissDialog();
                        } else {
                            savePictureToAlbum();
                        }
                    }
                });
        dialog.setNegativeButton(android.R.string.cancel,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        dialog.show();
    }

    private final int CODE_REQUEST_WRITESD_PERMISSION = 8800;

    private CWDialog getSDcardPermissDialog;

    /**
     * 获取SDcard权限提示框
     */
    private boolean showGetPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            savePictureToAlbum();
        } else {
            if (getSDcardPermissDialog == null) {
                getSDcardPermissDialog = new CWDialog(this);
                getSDcardPermissDialog.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog.setMessage(getString(R.string.get_album_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                        checkSDcardpermiss();
                    }
                });
                getSDcardPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                    }
                });
            }
            getSDcardPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用sd卡，判断权限
     */
    private boolean checkSDcardpermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, getString(R.string.read_and_write_local_storage_permissions));
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_WRITESD_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                savePictureToAlbum();
                            }
                        }
                    });
        } else {
            savePictureToAlbum();
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_REQUEST_WRITESD_PERMISSION:
                    showGetPermissDialog();
                    break;
            }
        }
    }

    /**
     * 保存图片到相册
     */
    private void savePictureToAlbum() {
        //保存图片到相册
        executeOtherThread(new Runnable() {
            @Override
            public void run() {
                try {
                    String imageName = ESystem.getCacheFileName("report", "jpg");
                    File tempFile = ESystem.getAlbumPicturesDir(ClassGradesActivity.this, imageName);
                    base64ToImage(savePicUrl, tempFile, imageName);
                } catch (IOException e) {
                    onSaveFailToast();
                    e.printStackTrace();
                } catch (Exception e) {
                    onSaveFailToast();
                    e.printStackTrace();
                }
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }

    // 将Base64字符串保存为图片
    private void base64ToImage(String base64String, File tempFile, String imageName) throws IOException {
        //这里需要注意，如果是标准的base64的字符串，需要截取，这里需要注意下
        byte[] decodedBytes = Base64.decode(base64String.split(",")[1], Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
        if (bitmap == null) {
            onSaveFailToast();
            return;
        }
        boolean isSaveSuccess;
//        if (Build.VERSION.SDK_INT < 29) {
//            //小于android 10版本
//            isSaveSuccess = saveImageToGallery(tempFile, bitmap, imageName);
//            onSaveSuccess(tempFile, imageName);
//        } else {
//            //android 10及以上版本
//            isSaveSuccess = saveImageToGalleryQ(tempFile, bitmap, imageName);
//        }
        isSaveSuccess = saveImageToGalleryQ(tempFile, bitmap, imageName);
        if (isSaveSuccess) {
            onSaveSuccessToast();
        } else {
            onSaveFailToast();
        }
    }

    /**
     * android 10 以下版本
     */
    private boolean saveImageToGallery(File file, Bitmap image, String imageName) {
        // 首先保存图片
        try {
            FileOutputStream fos = new FileOutputStream(file);
            // 通过io流的方式来压缩保存图片
            boolean isSuccess = image.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * android 10 以上版本
     */
    private boolean saveImageToGalleryQ(File file, Bitmap image, String imageName) {
        final ContentValues values = new ContentValues();
        // 设置图片名称
        values.put(MediaStore.Images.Media.DISPLAY_NAME, imageName);
        // 设置图片描述
        values.put(MediaStore.Images.Media.DESCRIPTION, imageName);
        // 设置图片格式
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");

        ContentResolver contentResolver = getContentResolver();
        final Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        try {
            if (uri != null) {
                // 将Uri转换为字节输出流
                java.io.OutputStream imageOut = contentResolver.openOutputStream(uri);
                // 使用JPEG格式将Bitmap图像写入输出流
                image.compress(Bitmap.CompressFormat.JPEG, 100, imageOut);
                // 关闭输出流
                imageOut.close();
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    private void onSaveSuccess(final File file, final String imageName) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ContentValues videoValues = new ContentValues();
                videoValues.put(MediaStore.Images.Media.TITLE, imageName);//imageName 图片名称
                videoValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                videoValues.put(MediaStore.Images.Media.DATA, file.getAbsolutePath()); //图片路径
                getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, videoValues);
                //这里记得必须加入更新图片
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
            }
        });
    }

    /**
     * 保存成功
     */
    private void onSaveSuccessToast() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ZToast.makeText(ClassGradesActivity.this, "保存成功", Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 保存失败
     */
    private void onSaveFailToast() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ZToast.makeText(ClassGradesActivity.this, "保存失败", Toast.LENGTH_LONG).show();
            }
        });
    }

    private Dialog shareBottomDialog;
    private TextView tx_share_hide_score;
    private TextView tx_share_show_score;
    private ImageView tx_share_setting_close;

    //显示分享弹框
    private void showshareBottomDialog() {
        shareBottomDialog = new Dialog(ClassGradesActivity.this, R.style.BottomDialog);
        View inflate = LayoutInflater.from(ClassGradesActivity.this).inflate(R.layout.activity_share_bottom_dialog, null);
        tx_share_hide_score = inflate.findViewById(R.id.tx_share_hide_score);
        tx_share_show_score = inflate.findViewById(R.id.tx_share_show_score);
        tx_share_setting_close = inflate.findViewById(R.id.tx_share_setting_close);
        shareBottomDialog.setContentView(inflate);
        Window window = shareBottomDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        ViewGroup.LayoutParams layoutParams = inflate.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        layoutParams.height = getResources().getDisplayMetrics().heightPixels / 4;
        inflate.setLayoutParams(layoutParams);
        window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
        window.setFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
        window.getDecorView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (null != shareBottomDialog) {
                    shareBottomDialog.dismiss();
                }
                return true;
            }
        });

        tx_share_setting_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null != shareBottomDialog) {
                    shareBottomDialog.dismiss();
                }
            }
        });
        tx_share_hide_score.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String hideOrShow = CWUtils.md5(workId + "_0");
                weixinShare(1, hideOrShow);
                if (null != shareBottomDialog) {
                    shareBottomDialog.dismiss();
                }
            }
        });
        tx_share_show_score.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String hideOrShow = CWUtils.md5(workId + "_1");
                weixinShare(1, hideOrShow);
                if (null != shareBottomDialog) {
                    shareBottomDialog.dismiss();
                }
            }
        });
        shareBottomDialog.show();
    }

    public static String toUtf8(String str) {
        String result = null;
        try {
            result = URLEncoder.encode(str, "UTF-8");
            result = result.replace("+", "%20");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    @Override
    protected void loadData() {
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }


    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        if (null != bridgeWebView) {
            bridgeWebView.destroy();
        }
        mRecorderHandler.removeCallbacksAndMessages(null);
        ALiYunManager.getInstance().unRegisterListener(aLiYunListener);
        super.onDestroy();
    }

    @Override
    public void finish() {
        if (null != bridgeWebView && bridgeWebView.canGoBack()) {
            bridgeWebView.goBack();// 返回前一个页面
        } else {
            super.finish();
        }
    }


    public void onEventMainThread(SubmitEvent submitEvent) {
        CWLog.d(TAG, "onEventMainThread+" + submitEvent.getId() + "--Json:" + submitEvent.getJson());
        if (submitEvent.getId().equals("JumpClassGrades")) {//
            /*JumpServiceParamBean jumpServiceParaBean = gson.fromJson(submitEvent.getJson(), JumpServiceParamBean.class);
            int serviceId = jumpServiceParaBean.getServiceId();
            String urlH5 = jumpServiceParaBean.getUrl();*/
            jumpToInnerResouce(submitEvent.getJson());
        }
    }

    /**
     * 跳入h5内部资源
     *
     * @param urlH5
     */
    public void jumpToInnerResouce(String urlH5) {
        if (!urlH5.contains("http")) {//解决连接中不包含http 导致闪退的bug
            urlH5 = "http://" + urlH5;
        }
        MeJumpManager.jumpToResourseCenterInnerH5Activity(R.string.go_back, this, urlH5);
    }

    //显示录音弹框
    private void showRecordBottomDialog() {
        recordBottomDialog = new Dialog(ClassGradesActivity.this, R.style.BottomDialog);
        View inflate = LayoutInflater.from(ClassGradesActivity.this).inflate(R.layout.activity_record_bottom_dialog, null);
        publish_dk_audio_stateView = inflate.findViewById(R.id.publish_dk_audio_stateView);
        dk_audio_complete = inflate.findViewById(R.id.dk_audio_complete);
        img_stop_recording = publish_dk_audio_stateView.findViewById(R.id.img_stop_recording);
        recordBottomDialog.setContentView(inflate);
        Window window = recordBottomDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        ViewGroup.LayoutParams layoutParams = inflate.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        layoutParams.height = getResources().getDisplayMetrics().heightPixels / 5;
        inflate.setLayoutParams(layoutParams);
        //设置录音图标是显示状态
        publish_dk_audio_stateView.setDKAutoRecordState(true);

        img_stop_recording.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stopRecord();
            }
        });

        window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
        window.setFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
        window.getDecorView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    tempMusicPath = "";
                    stopRecord();
                }
                return true;
            }
        });

        publish_dk_audio_stateView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showgetRecordPermissDialog();
            }
        });

        dk_audio_complete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tempMusicPath = "";
                stopRecord();
            }
        });
        recordBottomDialog.show();

    }

    public void stopRecord() {
        handler.removeCallbacks(stopRecordRunnable);
        if (null != recordBottomDialog) {
            recordBottomDialog.dismiss();
        }
        stopRecordView();
        //iEvaluateEngine.stop();
        try {
            if (mp3Recorder != null) {
                mp3Recorder.stop();
                mp3Recorder = null;
            }

        } catch (RuntimeException e) {
            if (mp3Recorder != null) {
                mp3Recorder.stop();
                mp3Recorder = null;
            }

            File file = new File(tempMusicPath);
            if (file.exists())
                file.delete();
        }
        if (null != tempMusicPath && !"".equals(tempMusicPath)) {
            addResult();
        }
        // iEvaluateEngine.stop();
        //stopRecordView();
        // setAudioImg();
    }

    /**
     * 获取Record权限提示框
     */
    private boolean showgetRecordPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.RECORD_AUDIO);
        if (isHavePermiss) {
            checkRecordAudioPermiss();
        } else {
            if (getRecordPermissDialog == null) {
                getRecordPermissDialog = new CWDialog(this);
                getRecordPermissDialog.setTitle(R.string.get_permiss_title);
                getRecordPermissDialog.setTitleTextColor(Color.BLACK);
                getRecordPermissDialog.setMessage(getString(R.string.get_record_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getRecordPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getRecordPermissDialog.dismiss();
                        checkRecordAudioPermiss();
                    }
                });
                getRecordPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getRecordPermissDialog.dismiss();
                    }
                });
            }
            getRecordPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用录音，判断权限
     */
    private boolean checkRecordAudioPermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.RECORD_AUDIO);
            //permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.RECORD_AUDIO, "录音权限");
            //noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "sdk权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_RECORD_AUDIO_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                record();
                            } else {
                                // showConfirmCommitDialog(getActivity(),
                                // "未获取到读写本地存储权限。");
                            }
                        }
                    });
        } else {
            record();
        }
        return true;
    }

    public void stopRecordView() {
        /*user_dk_audio_StateView_lay.setVisibility(View.GONE);
        dk_result_submit.setVisibility(View.VISIBLE);*/
        //user_dk_audio_img.stopOnlyRecord();
    }

    /**
     * 录音
     */
    protected void record() {
        // 开始录音
        try {
            publish_dk_audio_stateView.setTimeCount((long) 180000);
            publish_dk_audio_stateView.startUnAutoRecord();
            startRecord();
            // 开始线程，停止录音
            handler.postDelayed(stopRecordRunnable, 180000
            );
        } catch (OutOfMemoryError error) {
            isRecord = false;
            error.getStackTrace();
        }

    }

    public void startRecord() {
        tempMusicPath = ESystem.getMusicCacheDir(ClassGradesActivity.this, ESystem.getCacheFileName("workdetail", "mp3")).getAbsolutePath();
        mp3Recorder = new Mp3Recorder(tempMusicPath, BaseConstants.SAMPLERATE, mRecorderHandler);
        mp3Recorder.start();
    }

    /**
     * 上传音频
     *
     * @param
     * @param
     */
    public final void addResult() {
        File localImgFile = new File(tempMusicPath);
        if (localImgFile.exists()) {
            downloadMsg = "上传中，请稍等...";
            showDownloadProgress(downloadMsg);
            String photoUrlKey = ALiYunManager.getInstance()
                    .getDkworKey(tempMusicPath);
            ALiYunManager.getInstance().addDKFile(tempMusicPath, photoUrlKey,
                    TAG_AUDIO);
            CWLog.d("aliyun", "提交" + System.currentTimeMillis() + "tag="
                    + tempMusicPath);
        } else {
            ZToast.makeText(ClassGradesActivity.this, "音频不存在，请重新提交",
                    ZToast.LENGTH_SHORT).show();
        }
    }

    /**
     * @param type 1等于微信 2 等于朋友圈
     */
    private void weixinShare(int type, String hideOrShow) {
        try {
            WxShareHelper.getInstance().initWxShare(this, new WxShareListener() {
                @Override
                public void onWxShareing(String str) {
                    CWLog.d("Share==>> ", "ShareDialog onWxShareing：" + str);
                    System.out.println("Share==>> " + "ShareDialog onWxShareing：" + str);
                }

                @Override
                public void onWxShareSucc(String var) {
                    CWLog.d("Share==>> ", "ShareDialog onWxShareSucc成功：" + var);
                    System.out.println("Share==>> " + "ShareDialog onWxShareSucc成功：" + var);

                }

                @Override
                public void onWxShareFailure(int var, String var1) {
                    System.out.println("Share==>> " + "ShareDialog onWxShareFailure：" + var);
                    CWLog.d("Share==>> ", "ShareDialog onWxShareFailure：" + var);
                }

                @Override
                public boolean onWxShareCancel() {
                    System.out.println("Share==>> " + "ShareDialog onWxShareCancel：");
                    CWLog.d("Share==>> ", "ShareDialog onWxShareCancel：");
                    return false;
                }
            });
            ShareMsgObj shareMsgObj = new ShareMsgObj();
            shareMsgObj.setWxType(type);
            shareMsgObj.setShareType(ShareMsgObj.ShareType.SHARE_WEB);
            Bitmap bmp = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.share_ic_launcher);
            shareMsgObj.setThunbBmp(bmp);
            shareMsgObj.setUrl(shareParams.getLink() + "&type=" + hideOrShow);
            shareMsgObj.setMsgTitle(shareParams.getTitle());
            shareMsgObj.setMsgDesription(shareParams.getDesc());
            switch (type) {
                case 1:
                    break;
            }
            WxShareHelper.getInstance().sendReq(shareMsgObj);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
